package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankaccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class BankaccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankaccountService {


    /**
     * 新增或更新银行账号信息
     *
     * @param bankAccountUpsertReqDTO 银行账户信息
     */
    @Override
    @Transactional
    public void add(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        bankAccountUpsertReqDTO.setId(currentUser.getId());
        bankAccountUpsertReqDTO.setType(currentUser.getUserType());
        BankAccount bean = BeanUtil.toBean(bankAccountUpsertReqDTO,
                BankAccount.class);
        bean.setUpdateTime(LocalDateTime.now());

        BankAccount bankExit = getById(currentUser.getId());
        if(ObjectUtil.isEmpty(bankExit)){
            bean.setCreateTime(LocalDateTime.now());
        }
        saveOrUpdate(bean);
    }



    /**
     * 获取当前用户银行账号信息
     *
     * @return 银行账号信息
     */
    @Override
    public BankAccountResDTO getCurrentUserBankAccount() {
        BankAccount bankAccount = super.getOne(new QueryWrapper<BankAccount>().eq("id", UserContext.currentUserId()));
        if (ObjectUtil.isNull(bankAccount)) {
            throw new RuntimeException("当前用户没有绑定银行账户");
        }
        return BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
    }
}
